package com.cooge.statistics.common.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.fastjson.JSON;
import com.cooge.statistics.common.model.SystemSet;
import com.cooge.statistics.common.model.User;
import com.cooge.statistics.common.model.UserInfo;
import com.cooge.statistics.common.service.MainMenuService;
import com.cooge.statistics.common.service.UserInfoService;
import com.cooge.statistics.common.service.UserService;
import com.cooge.statistics.common.util.URLUtil;
@Controller
public class MainController {
	
	@Autowired
	UserService userService;
	
	@Autowired
	UserInfoService userInfoService;
	
	@Autowired
	MainMenuService mainMenuService;
	
	@RequestMapping(value = "login", method = RequestMethod.POST)
	public String loginp(HttpServletRequest request,HttpServletResponse response,User user) throws IOException{
			
			UsernamePasswordToken token =new UsernamePasswordToken(user.getName(),user.getPassword());
			try {
				SecurityUtils.getSubject().login(token);
				UserInfo ui = userInfoService.findByUserId(Integer.parseInt(String.valueOf(token.getPassword())));
				request.getSession().setAttribute(URLUtil.UID,ui);
				SystemSet systemSet =null;
				try {
					systemSet = JSON.parseObject(ui.getSystemset(),SystemSet.class);
					
				} catch (Exception e) {
					// TODO: handle exception
				}
				if(systemSet ==null){
					systemSet = new SystemSet();
				}
				request.getSession().setAttribute(URLUtil.SYSTEMSET,systemSet);
				return "redirect:index.html";
			} catch (Exception e) {
				e.printStackTrace();
				return "redirect:login.html";
			}
			
	}
	
	@RequestMapping(value = "login", method = RequestMethod.GET)
	public String login(HttpServletRequest request,HttpServletResponse response) throws IOException{
		return "login";
	}
	
	@RequestMapping(value = "logout", method = RequestMethod.GET)
	public String logout(HttpServletRequest request,HttpServletResponse response) throws IOException{
		request.getSession().invalidate();
		SecurityUtils.getSubject().logout();
		return "redirect:login.html";
	}
	
	@RequestMapping(value = "index", method = RequestMethod.GET)
	public String index(HttpServletRequest request,HttpServletResponse response) throws IOException{
		return "index";
	}

}
